/*
 * @Author: fanzhiwei
 * @Date: 2024-07-09 16:08:59
 * @LastEditors: fanzhiwei
 * @LastEditTime: 2024-07-19 09:08:11
 * @FilePath: /common-web-ui/src/store/modules/video.js
 * @Description:
 */
import store from "@/store";
import { getDevicePermission, sendHeartBeat } from "@/api/video";
const video = {
  state: {
    showRightView: false,
    showAlgorithmView: false,
    playWindowNum: 6,
    doDrawing: false,
    videoSettingId: false, //视频设置id
    watermark: false, //水印
    recordDownloadShow: 0, //录像下载弹窗
    recordDownloadDatas: [], //录像下载数据
    video3dSetting: 1, // 实时视频播放窗口的3D放大功能 1默认关闭 0 打开
    videoPlayer3dSetting: 1, // 视频播放组件的3D放大功能 1默认关闭 0 打开
    automaticEnlargedImages: 1, // 简约模式下自动加载放大图片（0是 1否）
    devicePermissions: {
      // 设备权限, 初始化兼容undefined, null, ""
      undefined: {},
      null: {},
      "": {},
    },
    // 设备转动触发
    deviceTurnOptions: {
      deviceCode: undefined, // 设备编码
      presetId: undefined, // 预置位
      ptz: undefined, // ptz
    },
    // 设备转动接收列表
    listenDeviceList: false,
    // 场景对象 { scene1, scene2, scene3, scene4 }
    scene: {},
  },
  mutations: {
    SET_SHOWRIGHTVIEW: (state, showRightView) => {
      state.showRightView = showRightView;
    },
    SET_SHOWALGORITHMVIEW: (state, showAlgorithmView) => {
      state.showAlgorithmView = showAlgorithmView;
    },
    SET_PLAYWINDOWNUM: (state, playWindowNum) => {
      state.playWindowNum = playWindowNum;
    },
    SET_DODRAWING: (state, doDrawing) => {
      state.doDrawing = doDrawing;
    },
    SET_WATERMARK: (state, watermark) => {
      state.watermark = JSON.parse(JSON.stringify(watermark));
    },
    SET_VIDEO3DSETTING: (state, video3dSetting) => {
      state.video3dSetting = video3dSetting;
    },
    SET_VIDEOPLAYER3DSETTING: (state, videoPlayer3dSetting) => {
      state.videoPlayer3dSetting = videoPlayer3dSetting;
    },
    SET_AUTOMATICENLARGEDIMAGES: (state, automaticEnlargedImages) => {
      state.automaticEnlargedImages = automaticEnlargedImages;
    },
    SET_VIDEOSETTINGID: (state, videoSettingId) => {
      state.videoSettingId = videoSettingId;
    },
  },
  actions: {
    /**
     * 录像下载
     */
    recordDownload({ state }, { show, datas = [] }) {
      state.recordDownloadShow = 0;
      state.recordDownloadDatas = datas;
      setTimeout(() => {
        state.recordDownloadShow = show;
      }, 50);
    },
    /**
     * 获取设备权限
     */
    async getDevicePermission({ state, dispatch }, deviceCode) {
      if (!deviceCode) {
        return;
      }
      // 默认不开起权限
      state.devicePermissions[deviceCode] = {
        control: false, // 云台操作状态
        preset: false, // 预置位操作状态
        patrol: false, // 巡航计划操作状态
        guard: false, // 看守卫操作状态
      };
      // 铁塔标识
      const isTT = !store.getters.userInfo.tenantId;
      if (isTT) {
        // 铁塔设备权限
        dispatch("devicePermissionForTT", deviceCode);
      } else {
        // 客户设备权限
        await dispatch("devicePermissionForTenant", deviceCode);
      }
      return state.devicePermissions;
    },
    /**
     * 铁塔设备权限
     */
    devicePermissionForTT({ state }, deviceCode) {
      const permissions = store.getters.permissions || [];
      state.devicePermissions[deviceCode] = {
        control: permissions.includes("video:videoControlRole"), // 云台操作状态
        preset: permissions.includes("video:videoPreset"), // 预置位操作状态
        patrol: permissions.includes("video:videoCruisePlan"), // 巡航计划操作状态
        guard: permissions.includes("video:videoGuard"), // 看守卫操作状态
      };
    },
    /**
     * 客户设备权限
     */
    async devicePermissionForTenant({ state }, deviceCode) {
      const resp = await getDevicePermission({
        configType: 2, //用户类型默认2
        deviceCode, // 摄像机编码
      });
      // 0: 开启, 1: 关闭
      const { cameraStatus, presetStatus, patrolStatus, guardStatus } =
        resp?.data || {};
      state.devicePermissions[deviceCode] = {
        control: cameraStatus !== "1", // 云台操作状态
        preset: presetStatus !== "1", // 预置位操作状态
        patrol: patrolStatus !== "1", // 巡航计划操作状态
        guard: guardStatus !== "1", // 看守卫操作状态
      };
    },
    /**
     * 设备转动
     */
    deviceTurn({ state }, option) {
      // 接收的数据, deviceCode: 设备编码, presetId: 预置位id, socket: 预置位到达推送标识
      const { deviceCode, presetId, ptz, socket } = option || {};
      // 赋值转动数据
      Object.assign(state.deviceTurnOptions, {
        deviceCode,
        presetId,
        ptz,
      });
      // 接收socket通知转发iframe场景通知
      if (socket) {
        document
          .querySelectorAll("iframe.iframe-container")
          .forEach((iframe) => {
            iframe.contentWindow.postMessage(
              {
                method: "deviceTurn",
                ...state.deviceTurnOptions,
              },
              iframe.src
            );
          });
      }
      clearTimeout(state.deviceTurnResetTiming);
      // 重置数据
      state.deviceTurnResetTiming = setTimeout(() => {
        Object.assign(state.deviceTurnOptions, {
          deviceCode: undefined,
          presetId: undefined,
          ptz: undefined,
        });
      }, 500);
    },
    /**
     * 设备转动接收通知设备列表
     * @param e
     * @param scene 场景对象 { scene1, scene2, scene3, scene4 }
     */
    listenDeviceTurn({ state, dispatch }, scene = {}) {
      // 开关未开启不执行
      if (!window.preset_arrival_notice_switch) {
        return;
      }
      const listenDeviceList = state.listenDeviceList;
      // 遍历接收的对象数据, 临时存储场景的数据
      Object.keys(scene).forEach((key) => {
        state.scene[key] = scene[key] || [];
      });
      // 整合所有的设备
      let list = [];
      Object.values(state.scene).forEach((item) => {
        list.push(...item);
      });
      // 无数据不执行
      if (!list.length) {
        state.listenDeviceList = false;
        return;
      }
      // 去重并赋值
      state.listenDeviceList = [...new Set(list)];
      // 未执行发送心跳才重新创建新的心跳
      if (listenDeviceList) {
        return;
      }
      dispatch("sendHeartBeat");
    },
    /**
     * 设备转动接收通知发送心跳 执行
     */
    sendHeartBeat({ state, dispatch }) {
      clearTimeout(state.sendHeartBeatTiming);
      if (!state.listenDeviceList?.length) {
        state.listenDeviceList = false;
        return;
      }
      sendHeartBeat({ deviceCodeList: state.listenDeviceList });
      state.sendHeartBeatTiming = setTimeout(() => {
        dispatch("sendHeartBeat");
      }, 5000);
    },
  },
};
export default video;
